<template>
	<el-tree ref="menuTree" :data="menuList" show-checkbox node-key="id" default-expand-all :props="defaultProps"></el-tree>
	<el-button @click="onAuthMenu">确定</el-button>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElTree } from 'element-plus'
import { api } from '@/api/index'
const { RequestMenu, RequestAuthorRole } = api
const menuList = ref<Array<Tree>>([])
const selectMenuList = ref<Array<Tree>>([])
const menuTree = ref()
interface Tree {
	id: number
	label: string
	children?: Tree[]
}
// 定义树形菜单节点属性
const defaultProps = {
	children: 'children',
	label: 'label'
}
const props = defineProps({
	roleId: Number
})
onMounted(() => {
	getMenuList()
})

/**
 * 所有权限列表
 */
const getMenuList = async () => {
	const rootRoleId = 1 //超级管理员roleId:1,返回所有菜单数据
	const data = await RequestMenu(rootRoleId)
	const { resultCode, resultInfo } = data
	if (resultCode === 1) {
		menuList.value = resultInfo

		setSelectorMenuList()
	}
}

/**
 * 当前角色菜单权限
 */
const setSelectorMenuList = () => {
	const currentRoleId: number = Number(props.roleId) //当前角色Id

	RequestMenu(currentRoleId).then(data => {
		let { resultCode, resultInfo } = data
		if (resultCode == 1) {
			selectMenuList.value = resultInfo
			menuTree.value.setCheckedNodes(resultInfo)
		}
	})
}

/**
 * 设置菜单权限
 */
const onAuthMenu = async () => {
	const resType: number = 0 //resType: 0菜单资源, 2按钮资源
	const roleId: number = props.roleId || 0 //当前角色Id
	let nodes = menuTree.value.getCheckedNodes()
	nodes = nodes.map((item: any) => item.id)
	console.log(nodes)
	const ids: string = nodes.join(',')
	console.log('ids ', ids)
	const data = await RequestAuthorRole(roleId, ids, resType)
	let { resultCode } = data

	if (resultCode == 1) {
		ElMessage.success('设置权限成功!')
	}
}
</script>

<style scoped></style>
